<?php 
$lang="EN";
$company="elitech";
$id_employee="none";
$id_approvedoc="none";
$idgroupapprove="1351215692633";
$id_employee_last="";
$co=0;
$database = 'elihan';
//echo $database;
	try {
		ini_set('display_errors', 0);
		$connection = mysql_connect("1.234.53.52", "cam", "5678" ) ;
		if(!$connection){
			echo "khong connect duoc<br>";		
		}		
		if(!mysql_select_db($database,$connection)){	
			echo "khong select duoc db<br>";	
		}
		if(!mysql_query("SET CHARACTER SET 'utf8'", $connection)){	
			echo "khong set character<br>";	
		}
	} catch (Exception $e) {
		echo 'Loi';	
	}

	$result=mysql_query("SELECT * FROM sendingmail s WHERE s.`status`=0;");
if(mysql_num_rows($result)>0){
	$row = mysql_fetch_assoc($result);

	
	$lang=$row['lang'];
	$company=$row['company'];
	$id_employee=$row['id_employee'];
	$id_approvedoc=$row['id_approvedoc'];
	$idgroupapprove=$row['idgroupapprove'];
	$id_employee_last=$row['id_employee_last'];
	$co=$row['co'];
	$id=$row['id'];
	mysql_query("UPDATE sendingmail SET `status`='1' WHERE (id='".$id."')");
	
	echo $row['id'].'-'.$row['idgroupapprove'].'-'.$row['id_approvedoc'].'-'.$row['id_employee'].'-'.$row['lang'].'-'.$row['co'].'-'.$row['company'].'-';
	
	

	$connection = mysql_connect("1.234.53.52", "cam", "5678" ) ;
	mysql_select_db("elihan", $connection);
	mysql_query("set names 'utf8'");
	$selectdatabase = mysql_query("SELECT am.DatabaseName,am.Logo from ac_eli_manager am where am.KeyName='$company'  and am.`Status` = 2");
	$result = mysql_fetch_assoc($selectdatabase);
	$database = $result[DatabaseName];

	mysql_select_db($database, $connection);
	
	if (empty($lang) || $lang == "EN") {
		$value = "value/value_en.php";
	} else if($lang == "VN") {
		$value = "value/value_vn.php";
	}
	else {
		$value = "value/value_kr.php";
	}
	include($value);
	
	
	
	if($id_employee!="none" && $id_approvedoc!="none" ){
		
		$db =mysql_query("SELECT Email,FullName FROM employee e WHERE e.IDEmployee='$id_employee';");
		$result = mysql_fetch_assoc($db);
		$to = $result[Email];
		$fullname=$result[FullName];

		$query = mysql_query("select a.Tile,a.Content,e.Fullname,a.Timecreate,a.comment,a.EmployeePerforment,a.Description,a.IDTypeDoc,a.IDEmployee,a.Content2,a.purpose,
				a.TotalTime,a.TripDate,a.Location,a.IDGroupApprove,a.IDStatus from approvedoc a 
				inner join employee e on a.IDEmployee = e.IDEmployee where a.IDApproveDoc = '$id_approvedoc'");
	
	
		while ($row = mysql_fetch_array($query))
		{
			$dtitle = $row[Tile];
			
			$dcontent = $row[Content];
			
			$dtime = $row[Timecreate];
			$duser = $row[Fullname];
			$dcomment = $row[comment];
			$dperforment = $row[EmployeePerforment];
			$ddescription = $row[Description];
			$dtotalTime = $row[TotalTime];
			$dtripDate = $row[TripDate];
			$dlocation = $row[Location];
			$didgroupapprover = $row[IDGroupApprove];
			$didemployee = $row[IDEmployee];
			$dstatus = $row[IDStatus];
			$dtype=$row[IDTypeDoc];
			$dcontent2 = $row[Content2];
			$dpurpose = $row[purpose];
		}
	
   		$query1 = mysql_query("SELECT l.IDStatus,l.DateApprove,e.Fullname,l.Description,l.IDEmployee FROM listapprove l
                    						INNER JOIN employee e ON l.IDEmployee = e.IDEmployee
                    						WHERE l.IDGroupApprove = '".$idgroupapprove."'
                    						ORDER BY l.`Order` ASC;");
		// file 03-gmail.php
		
		//Nhúng thư viện phpmailer
		require_once('class.phpmailer.php');
		
		//Khởi tạo đối tượng
		$mail = new PHPMailer();
		
		$mail->IsSMTP(); // Gọi đến class xử lý SMTP
		//$mail->Host       = "mail.zend.vn"; // tên SMTP server
		$mail->SMTPDebug  = 2;                    // enables SMTP debug information (for testing)
		                                           // 1 = errors and messages
		                                           // 2 = messages only
		$mail->SMTPAuth   = true;                  // Sử dụng đăng nhập vào account
		$mail->SMTPSecure = "ssl";
		$mail->Host       = "smtp.gmail.com";     // Thiết lập thông tin của SMPT
		$mail->Port       = 465;                     // Thiết lập cổng gửi email của máy
		$mail->Username   = "elisoftmailserver@gmail.com"; // SMTP account username
		$mail->Password   = "1234567892727";         // SMTP account password
		
		//Thiet lap thong tin nguoi gui va email nguoi gui
		$mail->SetFrom('elisoftmailserver@gmail.com',$company);
		
		//Thiết lập thông tin người nhận
		$mail->AddAddress($to, $fullname);
		
		
		//Thiết lập email nhận email hồi đáp
		//nếu người nhận nhấn nút Reply
		//$mail->AddReplyTo("hiepkhach_dtanh@yahoo.com","Pham Vu Khanh");
		$mail->Subject    =  $company." - ".$l_approve." - ".$dtitle;
		
		//Thiết lập định dạng font chữ
		$mail->CharSet = "utf-8";
		$mail->IsHTML(true);
		
	
		
		
		
		
		$body = '<html><body>';

  		
  		
  		
		$jpg=array();
		
		$mang=explode('src="',$content);
		for($i=1;$i<count($mang);$i++){
		$mang1=explode('"',$mang[$i]);
		$jpg[]=$mang1[0];	
		}
		function download_remote_file_with_curl($file_url, $save_to)
				{
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_POST, 0); 
					curl_setopt($ch,CURLOPT_URL,$file_url); 
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
					$file_content = curl_exec($ch);
					curl_close($ch);
			 
					$downloaded_file = fopen($save_to, 'w');
					fwrite($downloaded_file, $file_content);
					fclose($downloaded_file);
			 
				}
		for($i=0;$i<count($jpg);$i++){
			download_remote_file_with_curl($jpg[$i], "$i.jpg");
			$mail->AddEmbeddedImage("$i.jpg", "my-attach$i", "$i.jpg");
			str_replace($jpg[$i], "cid:my-attach$i", $content);

		}
  		
  		
  		
  		
		//body
		if ($dtype==7)
			include 'content/form7.php';
		if ($dtype==12)
			include 'content/form12.php';
		if ($dtype==13)
			include 'content/form13.php';
		if ($dtype==14)
			include 'content/form14.php';
		if ($dtype==15)
			include 'content/form15.php';
		if ($dtype==16)
			include 'content/form16.php';
		if ($dtype==17)
			include 'content/form17.php';
		$bodyreference=$body;
		
			$body.="<form action='http://".$company.".myapprove.com/ERP-PC/approvemail.php' method='get'>
					<div style='margin-top:20px'>
					<input type='hidden' name='lang' value='$lang'/>
					<input type='hidden' name='company' value='$company'/>
					<input type='hidden' name='id_employee' value='$id_employee'/>
					<input type='hidden' name='idgroupapprove' value='$idgroupapprove'/>
					<input type='hidden' name='id_approvedoc' value='$id_approvedoc'/>
					".$l_comment." :  <textarea rows='2' cols='3' style='width:300px; vertical-align:middle; margin:0 10px' name='comment'></textarea>
					<select name='action'>
						<option value='approve'>".$l_approve."</option>
						<option value='reject'>".$l_reject."</option>
					</select>
					<input type='submit' name='submit' value='SUBMIT'/>			
					</div>
				</form>";
		$body .= '</body></html>';
		
		$mail->Body = $body;
		$mail->AltBody=$dtitle;
		
		if(!$mail->Send()) {
		  	echo "Mailer Error: " . $mail->ErrorInfo;
		} else {
		 	echo "Sent Approve=> ".$to.'; ';
		 	//mysql_query("UPDATE sendingmail SET `status`='1' WHERE (id='".$id."')");
		}
		
		//reference
		if($co==1){
			$queryRefer = mysql_query("SELECT e.Fullname,e.Email,e.IDEmployee FROM list_reference l , employee e 
 														WHERE l.id_group = '$idgroupapprove' AND l.id_manager='$id_employee_last' AND l.id_employee=e.IDEmployee;") ;
		                    				$reference=array();
		                    				while ($row1 = mysql_fetch_array($queryRefer))
		                    				{
		                    					$reference[]=array($row1[Fullname],$row1[Email],$row1[IDEmployee]);
		                    					$dnamereferences = $row1[Fullname];
		                    				}
			
			if(count($reference)>0){
				
				$mail = new PHPMailer();
				
				$mail->IsSMTP(); // Gọi đến class xử lý SMTP
				//$mail->Host       = "mail.zend.vn"; // tên SMTP server
				$mail->SMTPDebug  = 2;                    // enables SMTP debug information (for testing)
				                                           // 1 = errors and messages
				                                           // 2 = messages only
				$mail->SMTPAuth   = true;                  // Sử dụng đăng nhập vào account
				$mail->SMTPSecure = "ssl";
				$mail->Host       = "smtp.gmail.com";     // Thiết lập thông tin của SMPT
				$mail->Port       = 465;                     // Thiết lập cổng gửi email của máy
				$mail->Username   = "elisoftmailserver@gmail.com"; // SMTP account username
				$mail->Password   = "1234567892727";         // SMTP account password
				
				//Thiet lap thong tin nguoi gui va email nguoi gui
				$mail->SetFrom('elisoftmailserver@gmail.com',$company);
				
				//Thiết lập thông tin người nhận
				for($i=0;$i<count($reference);$i++){
					$mail->AddAddress($reference[$i][1], $reference[$i][0]);
				}
				$mail->Subject    =  $company." - ".$l_status_reference." - ".$dtitle;
				//Thiết lập định dạng font chữ
				$mail->CharSet = "utf-8";
				$mail->IsHTML(true);
				
				$bodyreference.="<form action='http://".$company.".myapprove.com/ERP-PC/referencemail.php' method='get'>
						<div style='margin-top:20px'>
						<input type='hidden' name='lang' value='$lang'/>
						<input type='hidden' name='company' value='$company'/>
						<input type='hidden' name='idgroupapprove' value='$idgroupapprove'/>";
						for($i=0;$i<count($reference);$i++){
								$bodyreference.="<input type='hidden' name='id_employee' value='".$reference[$i][2]."'/>";
						}
					
						$bodyreference.="<input type='submit' name='submit' value='SUBMIT'/>		
		
						</div>
					</form>";
				
				
				$bodyreference .= '</body></html>';
				
				$mail->Body = $bodyreference;
				$mail->AltBody=$dtitle;
				
				if(!$mail->Send()) {
				  echo "Mailer Error: " . $mail->ErrorInfo;
				} else {
				  echo "Sent Reference=> ";
				for($i=0;$i<count($reference);$i++){
					echo $reference[$i][1].' ; ';
				}
				  //mysql_query("UPDATE sendingmail SET `status`='1' WHERE (id='".$id."')");
				}
			}
		}

	}
	
	if($id_employee=="none" && $id_approvedoc=="none" ){
		if($co==1){
				$queryRefer = mysql_query("SELECT e.Fullname,e.Email,e.IDEmployee FROM list_reference l , employee e 
 														WHERE l.id_group = '$idgroupapprove' AND l.id_manager='$id_employee_last' AND l.id_employee=e.IDEmployee;") ;
		                    				$reference=array();
		                    				while ($row1 = mysql_fetch_array($queryRefer))
		                    				{
		                    					$reference[]=array($row1[Fullname],$row1[Email],$row1[IDEmployee]);
		                    					$dnamereferences = $row1[Fullname];
		                       				
		                        
		                    				}
			if(count($reference)>0){
				//echo "da vao day";
				$query = mysql_query("select a.IDApproveDoc,a.Tile,a.Content,e.Fullname,a.Timecreate,a.comment,a.EmployeePerforment,a.Description,a.IDTypeDoc,a.IDEmployee,a.Content2,a.purpose,
						a.TotalTime,a.TripDate,a.Location,a.IDGroupApprove,a.IDStatus from approvedoc a 
						inner join employee e on a.IDEmployee = e.IDEmployee where a.IDGroupApprove = '$idgroupapprove'");
			
			
			
				while ($row = mysql_fetch_array($query))
				{
					$id_approvedoc= $row[IDApproveDoc];
					$dtitle = $row[Tile];
					$dcontent = $row[Content];
					$dtime = $row[Timecreate];
					$duser = $row[Fullname];
					$dcomment = $row[comment];
					$dperforment = $row[EmployeePerforment];
					$ddescription = $row[Description];
					$dtotalTime = $row[TotalTime];
					$dtripDate = $row[TripDate];
					$dlocation = $row[Location];
					$didgroupapprover = $row[IDGroupApprove];
					$didemployee = $row[IDEmployee];
					$dstatus = $row[IDStatus];
					$dtype=$row[IDTypeDoc];
					$dcontent2 = $row[Content2];
					$dpurpose = $row[purpose];
				}
			
		   		$query1 = mysql_query("SELECT l.IDStatus,l.DateApprove,e.Fullname,l.Description,l.IDEmployee FROM listapprove l
		                    						INNER JOIN employee e ON l.IDEmployee = e.IDEmployee
		                    						WHERE l.IDGroupApprove = '".$idgroupapprove."'
		                    						ORDER BY l.`Order` ASC;");
				// file 03-gmail.php
				
				//Nhúng thư viện phpmailer
				require_once('class.phpmailer.php');
				
				//Khởi tạo đối tượng
				$mail = new PHPMailer();
				
				$mail->IsSMTP(); // Gọi đến class xử lý SMTP
				//$mail->Host       = "mail.zend.vn"; // tên SMTP server
				$mail->SMTPDebug  = 2;                    // enables SMTP debug information (for testing)
				                                           // 1 = errors and messages
				                                           // 2 = messages only
				$mail->SMTPAuth   = true;                  // Sử dụng đăng nhập vào account
				$mail->SMTPSecure = "ssl";
				$mail->Host       = "smtp.gmail.com";     // Thiết lập thông tin của SMPT
				$mail->Port       = 465;                     // Thiết lập cổng gửi email của máy
				$mail->Username   = "elisoftmailserver@gmail.com"; // SMTP account username
				$mail->Password   = "1234567892727";         // SMTP account password
				
				//Thiet lap thong tin nguoi gui va email nguoi gui
				$mail->SetFrom('elisoftmailserver@gmail.com',$company);
				
				//Thiết lập thông tin người nhận
				
				
				
				//Thiết lập email nhận email hồi đáp
				//nếu người nhận nhấn nút Reply
				//$mail->AddReplyTo("hiepkhach_dtanh@yahoo.com","Pham Vu Khanh");
				$mail->Subject    =  $company." - ".$l_status_reference." - ".$dtitle;
				
				//Thiết lập định dạng font chữ
				$mail->CharSet = "utf-8";
				$mail->IsHTML(true);
				
				function download_remote_file_with_curl($file_url, $save_to)
				{
					$ch = curl_init();
					curl_setopt($ch, CURLOPT_POST, 0); 
					curl_setopt($ch,CURLOPT_URL,$file_url); 
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
					$file_content = curl_exec($ch);
					curl_close($ch);
			 
					$downloaded_file = fopen($save_to, 'w');
					fwrite($downloaded_file, $file_content);
					fclose($downloaded_file);
			 
				}
		//download_remote_file_with_curl('http://elitech.myapprove.com/upload/r.jpg', 'file.jpg');
		
		
		//$mail->AddEmbeddedImage("file.jpg", "my-attach", "file.jpg");
		
		$body = '<html><body>';
  		//$body.='Your <b>HTML</b> with an embedded Image: <img src="cid:my-attach"> Here is an image!';
				//body
				if ($dtype==7)
					include 'content/form7.php';
				if ($dtype==12)
					include 'content/form12.php';
				if ($dtype==13)
					include 'content/form13.php';
				if ($dtype==14)
					include 'content/form14.php';
				if ($dtype==15)
					include 'content/form15.php';
				if ($dtype==16)
					include 'content/form16.php';
				if ($dtype==17)
					include 'content/form17.php';
				
					$body.="<form action='http://".$company.".myapprove.com/ERP-PC/referencemail.php' method='get'>
							<div style='margin-top:20px'>
							<input type='hidden' name='lang' value='$lang'/>
							<input type='hidden' name='company' value='$company'/>
							
							<input type='hidden' name='idgroupapprove' value='$idgroupapprove'/>";
					
					for($i=0;$i<count($reference);$i++){
							$body.="<input type='hidden' name='id_employee' value='".$reference[$i][2]."'/>";
					}
					
							$body.="<input type='submit' name='submit' value='SUBMIT'/>			
							</div>
						</form>";
				$body .= '</body></html>';
				
				for($i=0;$i<count($reference);$i++){
						$mail->AddAddress($reference[$i][1], $reference[$i][0]);
				}
				$mail->Body = $body;
				$mail->AltBody=$dtitle;
				
				if(!$mail->Send()) {
				  echo "Mailer Error: " . $mail->ErrorInfo;
				} else {
				 echo "Sent Reference=> ";
					for($i=0;$i<count($reference);$i++){
						echo $reference[$i][1].' ; ';
					}
				  //mysql_query("UPDATE sendingmail SET `status`='1' WHERE (id='".$id."')");
				}
			}
		}
	}
	echo '<br/>';
	

}
mysql_close($connection);
?>